import { ref, computed } from "vue";

export default function useEditTodo(todosRef) {
  //表示当前修改的是哪一个
  const editingTodoRef = ref(null);
  let originTitle = null;
  const editTodo = (todo) => {
    originTitle = todo.title;
    editingTodoRef.value = todo;
  };
  const doneEdit = (todo) => {
    editingTodoRef.value = null;
    //去掉首尾空格
    const title = todo.title.trim();
    if (title) {
      todo.title = title;
    } else {
      //删除
      todosRef.value.splice(todosRef.value.index(todo), 1);
    }
  };
  const cancelEdit = (todo) => {
    editingTodoRef.value = null;
    todo.title = originTitle;
  };

  const allDoneRef = computed({
    //判断是否全部完成
    get() {
      return todosRef.value.filter((it) => !it.completed).length === 0;
    },
  });
  const setAllChecked = (checked) => {
    todosRef.value.forEach((todo) => {
      todo.completed = checked;
    });
  };

  return {
    editingTodoRef,
    editTodo,
    doneEdit,
    cancelEdit,
    allDoneRef,
    setAllChecked,
  };
}
